package com.github.ecbp.common.utils;


import com.github.ecbp.common.api.IErrorCode;
import com.github.ecbp.common.exception.base.BusinessException;

import java.util.Collection;
import java.util.function.Supplier;

public class Asserts {

    public Asserts() {
    }

    public static void checkNotNull(Object obj, IErrorCode respEnum) {
        if (obj == null || obj.equals("")) {
            throw BusinessException.fail(respEnum);
        }
    }


    public static <T> T checkNotNull(Supplier<T> action, IErrorCode respEnum) {
        T obj = action.get();
        checkNotNull(obj, respEnum);
        return obj;
    }


    public static void checkArgument(boolean flag, IErrorCode respEnum) {
        if (!flag) {
            throw BusinessException.fail(respEnum);
        }
    }


    public static void checkArgument(boolean flag, IErrorCode respEnum, Runnable doOtherAction) {
        if (!flag) {
            doOtherAction.run();
            throw BusinessException.fail(respEnum);
        }
    }

    public static void checkListNotNull(Collection collection, IErrorCode respEnum) {
        if (collection == null || collection.size() < 1) {
            throw BusinessException.fail(respEnum);
        }
    }


    public static void checkListNull(Collection collection, IErrorCode CodeAndMessage) {
        if (collection != null && collection.size() > 0) {
            throw BusinessException.fail(CodeAndMessage);
        }
    }


    public static void isTrue(boolean flag, IErrorCode respEnum) {
        if (!flag) {
            throw BusinessException.fail(respEnum);
        }
    }

    /**
     * sql执行影响行数小于1时抛出异常
     */
    public static void checkHandle(int result, IErrorCode respEnum) {
        isTrue(result > 0, respEnum);
    }
}
